package cn.linstudy.mq;

import cn.linstudy.config.WebSocketServer;
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.client.WebSocketClient;

/**
 * @Description
 * @Author XiaoLin
 * @Date 2021/5/21 14:58
 */
@Component
@RocketMQMessageListener(
    consumerGroup = "MQSeckillResultListener",
    topic = MQConstant.ORDER_RESULT_TOPIC
)
@Slf4j
public class MQSeckillResultListener implements RocketMQListener<OrderMQResult> {

  @Override
  public void onMessage(OrderMQResult orderMQResult) {
    log.info("进入到通知队列中");
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    // 找到客户端去推送数据
    WebSocketServer webSocketServer = WebSocketServer.clients.get(orderMQResult.getToken());
    if (webSocketServer!= null){
      try {
        webSocketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
